package com.wanglei.ssm.dao;

import com.wanglei.ssm.domain.Role;
import org.apache.ibatis.annotations.*;

import java.util.List;

/**
 * 角色数据操作对象
 *
 * @author wl
 */
public interface RoleDao {

    /**
     * 根据用户id,查询其角色信息和资源权限信息
     *
     * @param userId 用户id
     * @return 角色信息和资源权限信息
     */
    @Select("select * from role where id in (select roleId from users_role where userId = #{userId})")
    @Results(id = "roleMap", value = {
            @Result(id = true, property = "id", column = "id"),
            @Result(property = "roleName", column = "roleName"),
            @Result(property = "roleDesc", column = "roleDesc"),
            @Result(property = "permissions", column = "id", many = @Many(select = "com.wanglei.ssm.dao.PermissionDao.findPermissionByRoleId"))
    })
    List<Role> findRoleByUserId(String userId);

    /**
     * 查询所有角色信息
     *
     * @return 角色信息集合
     * @throws Exception e
     */
    @Select("select * from role")
    List<Role> queryAll() throws Exception;

    /**
     * 插入角色信息
     *
     * @param role 角色信息
     * @throws Exception e
     */
    @Insert("insert into role(roleName,roleDesc) values(#{roleName},#{roleDesc})")
    void insertRole(Role role) throws Exception;

    /**
     * 根据用户id查询未被其引用的角色信息
     *
     * @param id 用户id
     * @return 角色信息集合
     */
    @Select("select * from role where id not in (select roleId from users_role where userId = #{id})")
    List<Role> findOtherRole(String id) throws Exception;

    /**
     * 根据角色id查询角色和资源权限信息
     *
     * @param roleId 角色id
     * @return 角色及资源权限信息
     * @throws Exception e
     */
    @Select("select * from role where id = #{roleId}")
    @ResultMap(value = {"roleMap"})
    Role findById(String roleId) throws Exception;

    /**
     * 添加资源权限给角色
     *
     * @param roleId       角色id
     * @param permissionId 资源权限id
     */
    @Insert("insert into role_permission(roleId,permissionId) values(#{roleId},#{permissionId})")
    void addPermissionToRole(@Param("roleId") String roleId, @Param("permissionId") String permissionId);
}
